package com.example.threadstack;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static com.example.threadstack.Utils.getCurrentTime;

@RestController
@RequestMapping("redis")
public class RedisTestController {
    private ExecutorService executorService = Executors.newCachedThreadPool(new BasicThreadFactory
            .Builder()
            .namingPattern("Redis-Read-%d")
            .build()
    );

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("{loop}")
    public DeferredResult<String> loop(@PathVariable Integer loop){
        DeferredResult<String> result = new DeferredResult<>(10 * 1000L, "TimeOut");
        CompletableFuture.supplyAsync(()->{
            for (int i=0;i<loop;i++){
                stringRedisTemplate.boundValueOps("currentTime").set(getCurrentTime());
            }
            return stringRedisTemplate.boundValueOps("currentTime").get();
        }, executorService).thenAccept(r->result.setResult(r));

        return result;

    }

}
